package com.gpay.erp.services.purchase.impl;

import com.gpay.erp.core.dao.BaseDao;
import com.gpay.erp.core.dao.page.PagerModel;
import com.gpay.erp.services.common.SystemCommonService;
import com.gpay.erp.services.common.impl.StringUtil;
import com.gpay.erp.services.purchase.ApplicationService;
import com.gpay.erp.services.purchase.ApplicationSubService;
import com.gpay.erp.services.purchase.ContractService;
import com.gpay.erp.services.purchase.ContractSubService;
import com.gpay.erp.services.purchase.bean.Application;
import com.gpay.erp.services.purchase.bean.ApplicationSub;
import com.gpay.erp.services.purchase.bean.Contract;
import com.gpay.erp.services.purchase.bean.ContractSub;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Administrator on 2015/10/22 0022.
 */
@Service
public class ApplicationServiceImpl implements ApplicationService {
    @Resource
    private BaseDao dao;
    @Autowired
    private ApplicationSubService applicationSubService;
    @Autowired
    private ContractService contractService;
    @Autowired
    private ContractSubService contractSubService;
    @Autowired
    private SystemCommonService systemCommonService;

    public void setDao(BaseDao dao) {
        this.dao = dao;
    }

    @Override
    public int insert(Application application) {
        return dao.insert("application.insert", application);
    }

    @Override
    public int delete(Application application) {
        return 0;
    }

    @Override
    public int deletes(String[] ids) {
        return 0;
    }

    @Override
    public int update(Application application) {
        return dao.update("application.update", application);
    }

    @Override
    public Application selectOne(Application application) {
        return null;
    }

    @Override
    public Application selectById(String id) {
        return (Application) dao.selectOne("application.selectById", id);
    }

    @Override
    public PagerModel selectPageList(Application application) {
        return dao.selectPageList("application.selectPageList",
                "application.selectPageCount", application);
    }

    @Override
    public List<Application> selectList(Application application) {
        return null;
    }

    @Override
    public int getCount(Application application) {
        return dao.getCount("application.selectPageCount", application);
    }

    @Override
    public int updateApplicationById(Application application) {
        return dao.update("application.updateById", application);
    }

    public String getApplicationNumber() {

        String strCode = systemCommonService.saveSelectByName("APP001");
        return strCode;
    }

    /**
     *修改提交
     * @param id 主键id
     * @param status 提交状态
     * @return
     */
    public int updateCommitStatus(String id, String status) {
        Application application = new Application();
        application.setStatus(status);
        application.setId(id);
        int ida = updateApplicationById(application); //修改主表状态
        if ("1".equals(status)||"2".equals(status)||"3".equals(status)) {  //提交或者撤销提交，审核不通过
            if (ida != 1) {
                ApplicationSub applicationSub = new ApplicationSub();
                applicationSub.setF_appid(id);
                applicationSub.setStatusSub(status);
                int returnV = applicationSubService.updateApplicationSubByFId(applicationSub);//修改字表状态
            }
        }else if("0".equals(status)){ // 撤销状态 修改子表所有状态为0，重新计算子表各项状态，更新主表各项状态总和
            if (ida != 1) {
                ApplicationSub applicationSub = new ApplicationSub();
                applicationSub.setF_appid(id);
                applicationSub.setStatusSub(status);
                int returnV = applicationSubService.updateApplicationSubByFId(applicationSub); //修改字表状态
                Application application1 = getTotalValueAppliction(id, ""); //重新计算主表金额信息
                returnV =update(application1); //修改主表账户信息
            }
        }else if("4".equals(status)){
            if (ida != 1) {
                ApplicationSub applicationSub = new ApplicationSub();
                applicationSub.setF_appid(id);
                applicationSub.setStatusSub(status);
                int returnV = applicationSubService.updateApplicationSubByFId(applicationSub);//修改字表状态
                saveContracts(id);//生成采购合成
            }
        }
        return ida;
    }


    /**
     *修改保存
     * 修改新增的状态
     * 修改主表信息
     * 判断子项id是否存在，如果存在update 不存在insert
     * @param application 主表
     * @param applicationSubList 子表
     * @return
     */
    public int saveUpdateApplicationSub(Application application, List<ApplicationSub> applicationSubList) {
        application.setStatus("1");
        int updateId = update(application);
        if(updateId !=1){
           for (ApplicationSub applicationSub:applicationSubList){ //第一步跟新
               if(null != applicationSub.getId())
               {
                   applicationSub.setSubContractCode(applicationSub.getSubApplicationNumber());
                   applicationSubService.update(applicationSub);
               }

           }
            //第二步插入
            for (ApplicationSub applicationSub:applicationSubList){
                int counts = applicationSubService.selectListByfid(application.getId()).size();
                if("".equals(applicationSub.getId())||null == applicationSub.getId())
                {
                    counts++;
                    applicationSub.setF_appid(application.getId());
                    applicationSub.setStatusSub("1");
                    String subNumber = application.getApplicationNumber()+ StringUtil.getFormatNumber(String.valueOf(counts));
                    applicationSub.setSubApplicationNumber(subNumber);
                    applicationSub.setSubContractCode(subNumber);
                    applicationSubService.insert(applicationSub);
                }

            }
        }
        return updateId;
    }

    /**
     * 删除一行 保存信息
     * @param fid  删除的主表id
     * @param ids  删除的子表id
     * @return
     */
    public int deleteOneApplicationSub(String fid,List<String> ids) {
        ApplicationSub applicationSub = new ApplicationSub();
        applicationSub.setStatusSub("0");
        int reTurn = 1;
        for (String id:ids)
        {
            applicationSub.setId(id);
            applicationSubService.updateApplicationSubById(applicationSub);//撤销
        }
        Application application =getTotalValueAppliction(fid, "0");//根据子项所有状态是否都是撤销 都是撤销返回null
        if(application==null) //合同主表是撤销状态 重新计算合同主表合计金额
        {
            application =getTotalValueAppliction(fid, "");//重新获取主表账户统计
            application.setStatus("0");
            reTurn = update(application);  //修改主表所有信息
        }
        else {
            reTurn = update(application);  //直接修改主表所有信息
        }
        return  reTurn;
    }

    @Override
    public int saveApplicationSubList(Application application, List<ApplicationSub> applicationSubList) {
        int insertId = insert(application);
        int counts =1;
        if(insertId !=1){
            for (ApplicationSub applicationSub:applicationSubList){
                applicationSub.setF_appid(String.valueOf(insertId));
                applicationSub.setSubApplicationNumber(applicationSubService.getApplicationSubNumber(application.getApplicationNumber())+counts);
                applicationSub.setSubContractCode(applicationSubService.getApplicationSubNumber(application.getApplicationNumber())+counts);
                applicationSubService.insert(applicationSub);
                counts++;
            }
        }
        return insertId;
    }

    /**
     * 获取子项所有字段之和
     * @param id  主表外键id
     * @param status 查询的状态 0 不等于撤销的子项状态； '' 表示所有的撤销状态
     * @return
     */
    public Application getTotalValueAppliction(String id,String status) {
        Application application = selectById(id); //查询申请主表字段
        ApplicationSub applicationSub = new ApplicationSub();
        applicationSub.setStatusSub(status);
        applicationSub.setF_appid(id);
        Double totalAmount=0.0;//总金额
        Double totalWeight=0.0;//总重量
        Double taxGoodsAmount=0.0;//含税货款金额
        Double taxAmount=0.0;//税额
        HashMap hashMap = applicationSubService.selectTotalByOne(applicationSub);
        if(hashMap !=null){
            if (hashMap.get("TOTALCOST") != null) {
                totalAmount=(Double.parseDouble(hashMap.get("TOTALCOST").toString()));
            }
            if (hashMap.get("WEIGHT") != null) {
                totalWeight=(Double.parseDouble(hashMap.get("WEIGHT").toString()));
            }
            if (hashMap.get("PAYMENTAMOUNT") != null) {
                taxGoodsAmount=(Double.parseDouble(hashMap.get("PAYMENTAMOUNT").toString()));
            }
            if (hashMap.get("SUBTAXAMOUNT") != null) {
                taxAmount=(Double.parseDouble(hashMap.get("SUBTAXAMOUNT").toString()));
            }
            application.setTotalAmount(totalAmount);
            application.setTotalWeight(totalWeight);
            application.setTaxGoodsAmount(taxGoodsAmount);
            application.setTaxAmount(taxAmount);
            return application;
        }else {
            return null;
        }
    }

    /**
     * 采购申请转换采购合同
     *
     * @return
     */
    public Contract getContract(String id) {
        Contract contract = new Contract();
        Application application = selectById(id);
        List<ApplicationSub> applicationSubs = applicationSubService.selectListByfid(id);
        contract.setApplicationNumber(application.getApplicationNumber());
        contract.setF_appId(application.getId());
        contract.setContractCode(contractService.getContractCode());//获取合同号
        contract.setContractStatus("1");
        contract.setF_providerid(application.getF_providerid());
        contract.setProviderName(application.getProviderName());
        contract.setProviderCode(application.getProviderCode());
        contract.setProviderContract(application.getProviderContract());
        contract.setF_userid(application.getF_userid());
        contract.setUserName(application.getUserName());
        contract.setSignDept(application.getSignDept());
        contract.setDocumentMaker(application.getDocumentMaker());
        contract.setContractDate(application.getContractDate());
        contract.setRemark(application.getRemark());
        contract.setTotalAmount(application.getTotalAmount());
        contract.setTotalWeight(application.getTotalWeight());
        contract.setTaxGoodsAmount(application.getTaxGoodsAmount());
        contract.setTaxAmount(application.getTaxAmount());
        contract.setTransportation(application.getTransportation());

        contract.setContractNature("1");
        contract.setAmountPaid(0.0);
        contract.setAmountApplication(0.0);
        contract.setAccountName(application.getAccountName());
        contract.setF_account(application.getF_account());
        return contract;
    }

    /**
     * 采购申请子项转换采购合同子项
     *并修改采购申请子项表合同子项状态
     * @return
     */
    public int saveContracts(String id) {
        Contract contract = getContract(id);//生成采购合同
        int cid = contractService.insert(contract);//入库

        List<ContractSub> contractSubList = new ArrayList<ContractSub>();
        List<ApplicationSub> applicationSubs = applicationSubService.selectListByfid(id);
        int counts = 1;
        for (ApplicationSub applicationSub : applicationSubs) {
            ContractSub contractSub = new ContractSub();
//			contractSub.setSubContractCode();
//            contractSub.setF_id(applicationSub.getId());
			contractSub.setContractNumber(contract.getContractCode());//获取合同号
            contractSub.setStatusSub("1");
            contractSub.setItemNo(applicationSub.getItemNo());
            contractSub.setWeight(applicationSub.getWeight());
            contractSub.setUnitPrice(applicationSub.getUnitPrice());
            contractSub.setPaymentAmount(applicationSub.getPaymentAmount());
            contractSub.setGoodsName(applicationSub.getGoodsName());
            contractSub.setF_pm_id(applicationSub.getF_pm_id());
            contractSub.setMarks(applicationSub.getMarks());
            contractSub.setCpspecification(applicationSub.getCpspecification());
            contractSub.setCdName(applicationSub.getCdName());
            contractSub.setF_cd_id(applicationSub.getF_cd_id());
            contractSub.setStandards(applicationSub.getStandards());
            contractSub.setQualityGrade(applicationSub.getQualityGrade());
            contractSub.setUnitWeight(applicationSub.getUnitWeight());
            contractSub.setUnitFreight(applicationSub.getUnitFreight());
            contractSub.setUnitIncidental(applicationSub.getUnitIncidental());
            contractSub.setOtherCost(applicationSub.getOtherCost());
            contractSub.setTotalIncidental(applicationSub.getTotalIncidental());
            contractSub.setTotalCost(applicationSub.getTotalCost());
            contractSub.setDeliveryMethod(applicationSub.getDeliveryMethod());
            contractSub.setCostMethod(applicationSub.getCostMethod());
            contractSub.setInvoiceRise(applicationSub.getInvoiceRise());
            contractSub.setTaxRate(applicationSub.getTaxRate());
            contractSub.setQualityNum(applicationSub.getQualityNum());
            contractSub.setAppSubContract(applicationSub.getAppSubContract());
            contractSub.setResourceNumber(applicationSub.getResourceNumber());
            contractSub.setRemark(applicationSub.getRemark());
            contractSub.setNumberPage(applicationSub.getNumberPage());
            contractSub.setResourceDetail(applicationSub.getResourceDetail());
            contractSub.setOperater(applicationSub.getOperater());
            contractSub.setStorageNumber(0);
            contractSub.setRealCapacity(0);
            contractSub.setSettledAmount(0);

            contractSub.setAccountName(applicationSub.getAccountName());
            contractSub.setF_account(applicationSub.getF_account());
            contractSub.setProviderName(contract.getProviderName());
            contractSub.setUserName(contract.getUserName());
            contractSub.setSignDept(contract.getSignDept());
            contractSub.setOrderDate(contract.getContractDate());
            contractSub.setSubContractCode(contract.getContractCode()+"00"+counts);

            applicationSub.setSubContractCode(contractSubService.getContractSubCode(contract.getContractCode())+counts); //采购申请表合同子项状态
            applicationSubService.update(applicationSub); //修改表
            contractSub.setF_id(String.valueOf(cid));
            contractSubService.insert(contractSub);
            counts++;
//            contractSubList.add(contractSub);
        }
        return cid;
    }
    /**
     * 采购申请子项转换采购合同子项
     *暂且不用次方法
     * @return
     */
    public List<ContractSub> getContractSub(String id) {
        Contract contract = getContract(id);//生成采购合同
        int cid = contractService.insert(contract);//入库

        List<ContractSub> contractSubList = new ArrayList<ContractSub>();
        List<ApplicationSub> applicationSubs = applicationSubService.selectListByfid(id);
        int counts = 1;
        for (ApplicationSub applicationSub : applicationSubs) {
            ContractSub contractSub = new ContractSub();
//			contractSub.setSubContractCode();
            contractSub.setF_id(applicationSub.getId());
//			contractSub.setContractNumber(applicationSub.);//获取合同号
//            contractSub.setStatusSub("1");
            contractSub.setItemNo(applicationSub.getItemNo());
            contractSub.setWeight(applicationSub.getWeight());
            contractSub.setUnitPrice(applicationSub.getUnitPrice());
            contractSub.setPaymentAmount(applicationSub.getPaymentAmount());
            contractSub.setGoodsName(applicationSub.getGoodsName());
            contractSub.setF_pm_id(applicationSub.getF_pm_id());
            contractSub.setMarks(applicationSub.getMarks());
            contractSub.setCpspecification(applicationSub.getCpspecification());
            contractSub.setCdName(applicationSub.getCdName());
            contractSub.setF_cd_id(applicationSub.getF_cd_id());
            contractSub.setStandards(applicationSub.getStandards());
            contractSub.setQualityGrade(applicationSub.getQualityGrade());
            contractSub.setUnitWeight(applicationSub.getUnitWeight());
            contractSub.setUnitFreight(applicationSub.getUnitFreight());
            contractSub.setUnitIncidental(applicationSub.getUnitIncidental());
            contractSub.setOtherCost(applicationSub.getOtherCost());
            contractSub.setTotalIncidental(applicationSub.getTotalIncidental());
            contractSub.setTotalCost(applicationSub.getTotalCost());
            contractSub.setDeliveryMethod(applicationSub.getDeliveryMethod());
            contractSub.setCostMethod(applicationSub.getCostMethod());
            contractSub.setInvoiceRise(applicationSub.getInvoiceRise());
            contractSub.setTaxRate(applicationSub.getTaxRate());
            contractSub.setQualityNum(applicationSub.getQualityNum());
            contractSub.setAppSubContract(applicationSub.getAppSubContract());
            contractSub.setResourceNumber(applicationSub.getResourceNumber());
            contractSub.setRemark(applicationSub.getRemark());
            contractSub.setNumberPage(applicationSub.getNumberPage());
            contractSub.setResourceDetail(applicationSub.getResourceDetail());
            contractSub.setOperater(applicationSub.getOperater());
            contractSub.setStorageNumber(0);
            contractSub.setRealCapacity(0);
            contractSub.setSettledAmount(0);

            contractSub.setAccountName(applicationSub.getAccountName());
            contractSub.setF_account(applicationSub.getF_account());


            contractSub.setSubContractCode(contract.getContractCode()+counts);

            applicationSub.setSubContractCode(contractSubService.getContractSubCode(contract.getContractCode())+counts); //采购申请表合同子项状态
            contractSub.setF_id(String.valueOf(cid));
            contractSubService.insert(contractSub);
            contractSubList.add(contractSub);
        }
        return contractSubList;
    }

    public int saveContract(String id) {
        Contract contract = getContract(id);//生成采购合同
        int cid = contractService.insert(contract);//入库
        if (cid != 0) {
            List<ContractSub> contractSubList = getContractSub(id); //生成采购合同子项
            int counts = 1;
            for (ContractSub contractSub : contractSubList)  //采购合同子项生成
            {
                contractSub.setSubContractCode(contract.getContractCode()+counts);
                contractSub.setF_id(String.valueOf(cid));
                contractSubService.insert(contractSub);
                counts++;
            }
        }
        return cid;
    }
}
